package com.lez.flowpractice2.viewmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.lez.flowpractice2.db.AppDatabase
import com.lez.flowpractice2.db.User
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

class UserViewModel(app:Application) : AndroidViewModel(app){

    //插入操作
   fun insert(uid:String,firstName:String,lastName:String){
       viewModelScope.launch {

           AppDatabase.getInstance(getApplication())
               .userDao()
               .insert(User(uid,firstName,lastName))

           Log.i("info","插入成功:${uid}")
       }
   }

    fun getAll(): Flow<List<User>> {
        Log.i("info","ssssss")
        return AppDatabase.getInstance(getApplication())
            .userDao()
            .getAll()
            .catch { e-> e.printStackTrace() }
            .flowOn(Dispatchers.IO)
    }
}